<template>
  <div class="productlist">
    <div
      class="product"
      v-for="item in productList"
      :key="item.id"
      @click="showProductInfo(item.id)"
    >
      <img :src="item.img_url" alt />
      <h1 class="product-title">{{item.title}}</h1>
      <div class="product-info">
        <p class="product-price">
          <span class="current-price">￥{{item.sell_price}}</span>
          <span class="old-price">￥{{item.market_price}}</span>
        </p>
        <p class="product-promotion">
          <span>热卖中</span>
          <span>仅剩{{item.stock_quantity}}件</span>
        </p>
      </div>
    </div>

    <mt-button type="danger" size="large" plain @click="getMoreProducts">加载更多</mt-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      productList: [], // 产品列表
      pageIndex: 1 //当前页码
    };
  },

  created() {
    this.getProductList();
  },

  methods: {
    //  获取1页产品列表
    getProductList() {
      this.$http.get("api/getgoods?pageindex=" + this.pageIndex).then(res => {
        if (res.body.status == 0) {
          this.productList = this.productList.concat(res.body.message);
        } else {
          Toast("Loading error...");
        }
      });
    },

    // 加载更多的产品
    getMoreProducts() {
      this.pageIndex++;
      this.getProductList();
    },

    // 访问产品详情的跳转函数
    showProductInfo(id) {
      this.$router.push({ name: "productInfo", params: { id } });
    }
  }
};
</script>

<style lang="scss" scoped>
.productlist {
  display: flex;
  flex-wrap: wrap;
  padding: 7px;
  justify-content: space-between;

  .product {
    text-align: left;
    width: 49%;
    border: 1px solid #ccc;
    box-shadow: 0 0 8px #ccc;
    margin: 3px 0;
    padding: 2px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: 280px;
    h1 {
      font-size: 14px;
    }

    img {
      width: 100%;
    }
  }

  .product-info {
    background-color: #ccc;
    p {
      margin: 0;
      padding: 5px;
    }
    .product-price {
      .current-price {
        font-size: 16px;
        color: red;
        font-weight: bold;
      }

      .old-price {
        text-decoration: line-through;
        font-size: 12px;
        margin-left: 10px;
      }
    }

    .product-promotion {
      display: flex;
      justify-content: space-between;
      font-size: 12px;
    }
  }
}
</style>